//201902104011王雪梦
package bysj.controller.basic;
import bysj.domain.GraduateProjectType;
import bysj.service.GraduateProjectTypeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
@Slf4j
@WebServlet("/graduateProjectType.ctl")
public class GraduateProjectTypeController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ///创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();

        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个教师对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseGraduateProjectType(id_int, response);
            } else {//请求中包含条件和分页信息，需要响应多个教师对象
                //读取分页信息，形成分页对象
                //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
                List<Condition> conditionList = getConditions(req_jsonObj);
                //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
                this.responseGraduateProjectTypes(response, conditionList, pagination);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            e.printStackTrace();
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage());
        }
    }
    /**
     * 获得代表查询条件的List对象
     * @param req_jsonObj 请求body对应的JSONObject对象
     * @return 代表查询条件的List对象
     */
    private List<Condition> getConditions(JSONObject req_jsonObj) {
        JSONArray conditionList_jsonArray =
                req_jsonObj.getJSONArray("conditionList");
        //条件对象
        List<Condition> conditionList = null;
        //如果有“conditionList”键
        if (conditionList_jsonArray != null) {
            //将描述条件的 JSONArray 对象转换为 Java的List 对象
            conditionList = conditionList_jsonArray.toJavaList(Condition.class);
        }
        return conditionList;
    }
    /**
     * 获得代表查询条件的Pagination对象
     * @param req_jsonObj 请求body对应的JSONObject对象
     * @return 代表查询条件的Pagination对象
     */
    private Pagination getPagination(JSONObject req_jsonObj) {
        JSONObject pagination_jsonObj =
                req_jsonObj.getJSONObject("pagination");
        //分页对象
        Pagination pagination = null;
        //如果有“pagination”键
        if (pagination_jsonObj != null) {
            //将描述分页的 JSONObject 对象转换为 Java 对象
            pagination = pagination_jsonObj
                    .toJavaObject(Pagination.class);
        }
        return pagination;
    }
    //响应一个毕业设计选题类型对象
    private void responseGraduateProjectType(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找毕业设计选题类型
        GraduateProjectType graduateProjectType = GraduateProjectTypeService.getInstance().find(id);
        String graduateProjectType_json = JSON.toJSONString(graduateProjectType);
        //响应degree到前端
        response.getWriter().println(graduateProjectType_json);
    }
    //响应所有学位对象
    private void responseGraduateProjectTypes(HttpServletResponse response,List<Condition>conditionList,Pagination pagination)
            throws ServletException, IOException, SQLException {
        //获得所有毕业设计选题类型
        Collection<GraduateProjectType> graduateProjectTypes = GraduateProjectTypeService.getInstance().findAll(conditionList,pagination);
        String graduateProjectTypes_json = JSON.toJSONString(graduateProjectTypes,SerializerFeature.DisableCircularReferenceDetect);
        //响应degrees到前端
        response.getWriter().println(graduateProjectTypes_json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String school_json = JSONUtil.getJSON(request);
        //将JSON字串解析为GraduateProjectType对象
        GraduateProjectType graduateProjectTypeToAdd = JSON.parseObject(school_json,GraduateProjectType.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加GraduateProjectType对象
        try {
            GraduateProjectTypeService.getInstance().add(graduateProjectTypeToAdd);
            message.put("message", "增加成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
        }catch(Exception e){
            message.put("message", "网络异常");
        }
        //响应message到前端
        response.getWriter().println(message);
    }
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //读取参数id
        String id_str = request.getParameter("id");
        int id = Integer.parseInt(id_str);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表中删除对应的毕业设计选题类型
        try {
            GraduateProjectTypeService.getInstance().delete(id);
            message.put("message","删除成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
        }catch(Exception e){
            message.put("message", "网络异常");
        }
        //响应message到前端
        response.getWriter().println(message);
    }
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String graduateProjectType_json = JSONUtil.getJSON(request);
        //将JSON字串解析为GraduateProjectType对象
        GraduateProjectType graduateProjectTypeToUpdate = JSON.parseObject(graduateProjectType_json,GraduateProjectType.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改GraduateProjectType对象对应的记录
        try {
            GraduateProjectTypeService.getInstance().update(graduateProjectTypeToUpdate);
            message.put("message", "修改成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
        }catch(Exception e){
            message.put("message", "网络异常");
        }
        //响应message到前端
        response.getWriter().println(message);
    }
}
